package com.feature.core.util;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.beans.BeanMap;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.feature.core.mybatis.IQuery;

public class MyBatisPlusUtil {
	public static final String LIST_SUFFIX = "List";
	public static final String TIME_START_SUFFIX = "TimeStart";
	public static final String TIME_END_SUFFIX = "TimeEnd";
	public static final String LIKE_SUFFIX = "Like";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> QueryWrapper<T> buildQueryWrapper(IQuery o, Map<String, BiConsumer<QueryWrapper<T>, Object>> propertyCustomer) {
		if (o == null) {
			return Wrappers.emptyWrapper();
		}
		QueryWrapper<T> wrapper = new QueryWrapper<T>();
		Map<String, Object> propertyValMap = BeanMap.create(o);
		propertyValMap.entrySet().stream().forEach(pv -> {
			Object val = pv.getValue();
			String key = pv.getKey();
			if (val != null && StringUtils.isNotBlank(val.toString())) {
				if (propertyCustomer != null && propertyCustomer.containsKey(key)) {
					propertyCustomer.get(key).accept(wrapper, val);
				} else if (Collection.class.isAssignableFrom(val.getClass())) {
					String property = Optional.of(key).filter(v -> v.contains(LIST_SUFFIX)).map(v -> v.substring(0, key.length() - LIST_SUFFIX.length())).orElse(key);
					String clomun = com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(property);
					wrapper.in(clomun, (Collection) val);
				} else if (key.endsWith(TIME_START_SUFFIX)) {
					String property = key.substring(0, key.length() - TIME_START_SUFFIX.length() + 4);
					String clomun = com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(property);
					wrapper.ge(clomun, val);
				} else if (key.endsWith(TIME_END_SUFFIX)) {
					String property = key.substring(0, key.length() - TIME_END_SUFFIX.length() + 4);
					String clomun = com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(property);
					wrapper.le(clomun, val);
				} else if (key.endsWith(LIKE_SUFFIX)) {
					String property = key.substring(0, key.length() - LIKE_SUFFIX.length());
					String clomun = com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(property);
					wrapper.like(clomun, val);
				} else {
					wrapper.eq(com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(key), val);
				}
			}
		});
		return wrapper;

	}

	public static <T> QueryWrapper<T> buildQueryWrapper(IQuery o) {
		return buildQueryWrapper(o, null);
	}
}
